﻿using System.Diagnostics;
using System.IO.Ports;
using Vanara;
namespace DataAcquisition.Main.Services
{
    /// <summary>
    /// 语音播报
    /// </summary>
    internal class BroadcastServices
    {
        /// <summary>
        /// 语音地址
        /// </summary>
        private string Port = string.Empty;

        /// <summary>
        /// 波特率
        /// </summary>
        private int BaudRate = 9600;

        /// <summary>
        /// 串口
        /// </summary>
        private SerialPort serialPort;

        /// <summary>播报状态
        /// 
        /// </summary>
        private bool BroadcastState = false;

        /// <summary>
        /// 开始配置
        /// </summary>
        public void Setup()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["name"] = "语音";
            List<Device> list = SqlHelper.Inquireable<Device>(where);
            if (list.Count > 0)
            {
                Device device = list[0];
                Port = device.Port;
                BaudRate = device.BaudRate;
                SetupSerialPort();
            }
            else
            {
                Log.Info("数据库未添加语音设备");
            }

        }

        /// <summary>
        /// 配置串口
        /// </summary>
        private void SetupSerialPort()
        {
            serialPort = new SerialPort(Port, BaudRate, Parity.None, 8, StopBits.One);
            serialPort.DataReceived += new SerialDataReceivedEventHandler(receivedData);//接收数据事件

            try
            {
                serialPort.Open();
                if (serialPort.IsOpen)
                {
                    Log.Info("语音端口已打开");
                    try
                    {
                        Byte[] strbyte = Tool.HexStringToBytes("0401FFFF");
                        serialPort.Write(strbyte, 0, strbyte.Length);//发送数据
                    }
                    catch (Exception ex)
                    {
                        Log.Error("语音模块连接指令下发异常：" + ex.Message);
                    }
                }
                else
                {
                    Log.Info("未打开语音端口");
                }
            }
            catch (Exception ex)
            {
                Log.Error("语音端口打开异常：" + ex.Message);
            }
        }

        /// <summary>收到串口回复
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void receivedData(object sender, SerialDataReceivedEventArgs e)//接收数据
        {
            SerialPort serialPort = (SerialPort)sender;

            int len = serialPort.BytesToRead;//获取可以读取的字节数

            byte[] buff = new byte[len];//创建缓存数据数组
            try
            {
                serialPort.Read(buff, 0, len);//把数据读取到buff数组

                string back = BitConverter.ToString(buff, 0, buff.Length).Replace("-", "");
                if (back.Contains("04"))
                {
                    Log.Info("语音模块已连接");
                    BroadcastState = true;
                }
            }
            catch (Exception ex)
            {
                Log.Error("读取串口回复数据异常：" + ex.Message);
            }
        }

        /// <summary>播报
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public void Broadcast(string content)
        {
            if (BroadcastState)
            {
                Task.Run(() => {
                    content = "#" + content;
                    string hexContent = Tool.GetHexFromChs(content);
                    Log.Debug(string.Format("播报：{0}，指令:{1}", content, hexContent));
                    if (serialPort.IsOpen)
                    {
                        Byte[] strbyte = Tool.HexStringToBytes(hexContent);
                        serialPort.Write(strbyte, 0, strbyte.Length);//发送数据
                    }
                    else
                    {
                        Log.Info("语音端口已断开，无法下发播报指令");
                    }
                });
            }
            else
            {
                Log.Info("启语音播报不可用");
            }
        }
    }
}
